package DAO;

import bean.Television;

import java.util.List;
import java.util.Map;

public class TelevisionDao extends BaseDao implements TelevisionDaoInterface {
    public List<Television> getAllTelevisions() {
        String sql = "SELECT id, name, price, screenSize, resolution, model, imageUrl, description FROM television";
        return queryForList(sql, Television.class);
    }

    public Television getTelevisionById(Integer id) {
        String sql = "SELECT id, name, price, screenSize, resolution, model, imageUrl, description FROM television WHERE id = ?";
        return queryForOne(sql, Television.class, id);
    }
    
    public int addTelevision(Television television) {
        String sql = "INSERT INTO television (name, price, screenSize, resolution, model, imageUrl, description) " +
                     "VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        // 执行插入操作
        int result = update(sql, 
            television.getName(),
            television.getPrice(),
            television.getScreenSize(),
            television.getResolution(),
            television.getModel(),
            television.getImageUrl(),
            television.getDescription()
        );
        
        if (result > 0) {
            // 获取最后插入的ID
            sql = "SELECT LAST_INSERT_ID()";
            Map<String, Object> map = queryForListMap(sql).get(0);
            return ((Number) map.get("LAST_INSERT_ID()")).intValue();
        }
        return -1;
    }
    
    public int updateTelevision(Television television) {
        String sql = "UPDATE television SET name = ?, price = ?, screenSize = ?, " +
                     "resolution = ?, model = ?, imageUrl = ?, description = ? WHERE id = ?";
        return update(sql, 
            television.getName(),
            television.getPrice(),
            television.getScreenSize(),
            television.getResolution(),
            television.getModel(),
            television.getImageUrl(),
            television.getDescription(),
            television.getId()
        );
    }
    
    public int deleteTelevision(Integer id) {
        String sql = "DELETE FROM television WHERE id = ?";
        return update(sql, id);
    }

    public List<Television> getTelevisionsBySubCategoryId(int subCategoryId) {
        String sql = "SELECT t.id, t.name, t.price, t.screenSize, t.resolution, t.model, t.imageUrl, t.description " +
                     "FROM television t " +
                     "JOIN subcategory_television st ON t.id = st.television_id " +
                     "WHERE st.sub_category_id = ?";
        return queryForList(sql, Television.class, subCategoryId);
    }
} 